// ActionScript file
import Modules.NavigationDetails;
import Modules.NavigationInfo;
import Modules.PostLogin;
import Modules.Windows.CMDWindow;
import Modules.Windows.ValidationErrorWin;

import com.desidea.common.CommonClass;
import com.desidea.common.CustomFormatter;
import com.desidea.components.grid.button.SuperGridButton;
import com.desidea.components.spinner.BusySpinner;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.DisplayModeSetter;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import flash.events.Event;
import flash.events.MouseEvent;

import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.LinkButton;
import mx.core.Application;
import mx.events.CloseEvent;
import mx.events.ValidationResultEvent;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;
import mx.validators.Validator;

private var _btnEditCancel:LinkButton;

private var _key:String = "";
private var _mode:String = SuperGridButton.MODE_VIEW;
private var _modeSet:Boolean = false;
private var _creationCompleted:Boolean = false;
private var cntctdetails:XML;
private var _accountGUID:String = "";

private var _cityLoaded:Boolean = false;
private var _detailsLoaded:Boolean = false;
private var _ni:NavigationInfo = null;

public function get mode():String{
	return _mode;
}

public function set mode(value:String):void{
	this._mode = value;
	this._modeSet = true;
}

public function get key():String{
	return _key;
}

public function set key(value:String):void{
	this._key = value;
}

public function get NavInfo():NavigationInfo{
	return _ni;
}

public function set NavInfo(value:NavigationInfo):void{
	this._ni = value;
}

public function get accountGUID():String{
	return _accountGUID;
}

public function set accountGUID(value:String):void{
	this._accountGUID = value;
}

private function windowCreated():void{

	_btnEditCancel = new LinkButton();
	_btnEditCancel.label = "Edit";	
	_btnEditCancel.height = this.pnlContactInfo.ToolBox.height - 2;
	_btnEditCancel.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('editdetails'); });
	this.pnlContactInfo.ToolBox.addChild(_btnEditCancel);
	this._creationCompleted = true;
	this.ctlCity.addEventListener("dataLoadComplete",cityDataLoaded);
	this.ctlCity.loadData(CommonClass.UserID);
	this.loadData();
	this.txtLastName.setFocus();
	
	_btnEditCancel.enabled = CommonClass.UserLoginInfo.CanCreateContact;
}

private function setScreenMode():void{
	if(!_creationCompleted) return;
	
	if(this.mode == SuperGridButton.MODE_VIEW || this.mode == SuperGridButton.MODE_VIEWICON){
		DisplayModeSetter.getInstance().setMode(this.frmContactInfo,false);
		btnSubmit.enabled = false;
		this.ctlCity.setMode(false);
		cmbAccountName.selectedItem = (cntctdetails.ACCOUNTS.entry.(@id == cntctdetails.RELATIONS.RELATION.(@type == "ACCOUNT"))[0]) as XML;
		this.lblTitle.text = "View Contact Details";
	}else if(this.mode == SuperGridButton.MODE_EDIT){		//MODE_EDIT = create new
		DisplayModeSetter.getInstance().setMode(this.frmContactInfo,true);
		btnSubmit.enabled = true;
		_btnEditCancel.enabled = false;
		
		cmbAccountName.enabled = true;
		cmbContactOwner.enabled = false;
		this.ctlCity.setMode(true);
		
		cmbContactOwner.selectedItem = (cntctdetails.USERS.entry.(@id == CommonClass.UserID.toString())[0]) as XML;
		this.lblTitle.text = "New Contact";
	}
}

private function init():void{
	this.txtNotes.linkTextInput.visible = false;
	this.txtNotes._RichTextEditor_VRule2.visible = false;
}

private function onClick(mode:String):void{
	switch(mode){
		case "editdetails":
			DisplayModeSetter.getInstance().setMode(this.frmContactInfo,true);
			btnSubmit.enabled = true;
			cmbAccountName.enabled = false;
			cmbContactOwner.enabled = false;
			_btnEditCancel.enabled = false;
			this.lblTitle.text = "Edit Contact Details";
			this.ctlCity.setMode(true);
			break;
		case "sendmail":
			navigateToURL( new URLRequest("mailto:"+this.txtEmailAddress.text),"_blank");
			break;
	}
}

private function buttonClick(eventType:String):void{
	switch(eventType){
		case "save":
			handleSubmitClick();
			break;
		case "cancel":
			handleCancelClick();
			break;
		default:
			Alert.show( "Yet to Implement : " + eventType);
	}
}

private function handleCancelClick():void{
	(this.parentDocument as CMDWindow).NavInfo = null;
	CommonClass.NextEvent = null;
	
	if(this.NavInfo!=null && this.NavInfo.sourceNavObj!=null){
		var src:NavigationDetails = (this.NavInfo.previousLink==null?null:this.NavInfo.previousLink.sourceNavObj.copy());// this.NavInfo.destinationNavObj.copy();
		var dst:NavigationDetails = this.NavInfo.sourceNavObj.copy();
		var ni:NavigationInfo = new NavigationInfo(src,dst);
		ni.previousLink = (this.NavInfo.previousLink == null? null:this.NavInfo.previousLink.previousLink);
		(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(ni);
	}else {
		(this.parentDocument as CMDWindow).loadModule();
	}
}

private function handleSubmitClick():void{
	if(validate()){
		saveData("", getPostData());
	}else{
		CommonClass.NextEvent = null;
	}
}


private function loadData():void{
	var params:String = "OPERATION=CONTACT_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key)) + 
						"&OWNERID="+CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForContactDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
}

private function callForContactDetails(event:ProcessServiceRequestResultEvent):void{
	cntctdetails = XML(event.result);
	if(cntctdetails.RESPONSE.RESULT == "E"){
		BusySpinner.getInstance().stop();
		Alert.show(cntctdetails.RESPONSE.MESSAGE);
	}else if(cntctdetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(cntctdetails);
		setScreenMode();
		_detailsLoaded = true;
		this.callLater(initializeForDirtyCheck);
	}
}

private function partnerServiceFaultHandler(event:FaultEvent):void{
	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

private function cityDataLoaded(event:Event):void{
	_cityLoaded = true;
	initializeForDirtyCheck();
}

private function setDataOnControls(response:XML):void{
	
	cmbAccountName.dataProvider = new XML(response.ACCOUNTS).entry as XMLList;
	cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@id == response.RELATIONS.RELATION.(@type == "ACCOUNT"))[0]) as XML;
	cmbAccountName.selectedIndex = (cmbAccountName.selectedIndex <0)?0:cmbAccountName.selectedIndex;
	
	cmbContactOwner.dataProvider = new XML(response.USERS).entry as XMLList;
	cmbContactOwner.selectedItem = (response.USERS.entry.(@id == response.RELATIONS.RELATION.(@type == "OWNER"))[0]) as XML
	cmbContactOwner.selectedIndex = (cmbContactOwner.selectedIndex <0)?0:cmbContactOwner.selectedIndex;

	cmbJobTitle.dataProvider = new XML(response.JOBTITLES).entry as XMLList;
	cmbJobTitle.selectedIndex = 0;
	cmbJobTitle.selectedItem = (response.JOBTITLES.entry.(@id == response.JOBTITLE)[0]) as XML;

//	cmbCity.dataProvider = new XML(response.CITIES).entry.(@active==1 || @id == response.CITYNO) as XMLList;
//	cmbCity.selectedIndex = 0;
//	cmbCity.selectedItem = (response.CITIES.entry.(@id == response.CITYNO)[0]) as XML

	cmbState.dataProvider = new XML(response.STATES).entry as XMLList;
	cmbState.selectedIndex = 0;

	CommonClass.setDataOnComponents(this.txtLastName, response);
	CommonClass.setDataOnComponents(this.txtFirstName, response);

	CommonClass.setDataOnComponents(this.txtAddress, response);
	cmbState.selectedItem = (response.STATES.entry.(@id == response.STATE)[0]) as XML
	CommonClass.setDataOnComponents(this.txtZipCode, response);

	CommonClass.setDataOnComponents(this.txtBusinessPhone, response);
	CommonClass.setDataOnComponents(this.txtExtension, response);
	CommonClass.setDataOnComponents(this.txtMobilePhone, response);
	CommonClass.setDataOnComponents(this.txtFaxNo, response);
	CommonClass.setDataOnComponents(this.txtEmailAddress, response);
	CommonClass.setDataOnComponents(this.txtNotes, response);
	CommonClass.setDataOnComponents(this.chkActive, response);
	
	this.ctlCity.SelectedCityNo = new Number(response.CITYNO);

	// DEFAULT DATA FROM ACCOUNTS FOR THE NEW CONTACT
	if(this.NavInfo.dataObj != null && this.key == ""){
		var dataXml:XML = (this.NavInfo.dataObj as XML);
		CommonClass.setDataOnComponents(this.txtAddress, dataXml);
		this.ctlCity.SelectedCityNo = new Number(dataXml.CITYNO);
		cmbState.selectedItem = (response.STATES.entry.(@id == dataXml.STATE)[0]) as XML
		CommonClass.setDataOnComponents(this.txtZipCode, dataXml);
		CommonClass.setDataOnComponents(this.txtBusinessPhone, dataXml);
		CommonClass.setDataOnComponents(this.txtFaxNo, dataXml);
	}

	this.key = response.PKID;
	
	txtBusinessPhone.text = CustomFormatter.getInstance().convertToPhoneString(txtBusinessPhone.text);
	txtMobilePhone.text = CustomFormatter.getInstance().convertToPhoneString(txtMobilePhone.text);
	txtFaxNo.text = CustomFormatter.getInstance().convertToPhoneString(txtFaxNo.text);

	if(this.accountGUID!=null && this.accountGUID.length >0){
		cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@guid == this.accountGUID.toUpperCase())[0]) as XML;
	}
}

private function getPostData():String{

	txtBusinessPhone.text = CustomFormatter.getInstance().convertToPhoneString(txtBusinessPhone.text);
	txtMobilePhone.text = CustomFormatter.getInstance().convertToPhoneString(txtMobilePhone.text);
	txtFaxNo.text = CustomFormatter.getInstance().convertToPhoneString(txtFaxNo.text);

	var postData:String = new String();

	postData += "CONTACTNO=" + (cntctdetails.CONTACTNO.toString())				+ "&";
	postData += "CONTACTGUID=" + (cntctdetails.CONTACTGUID.toString())			+ "&";

	postData += (CommonClass.preparePostString(this.cmbAccountName))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbContactOwner))			+ "&";

	postData += (CommonClass.preparePostString(this.txtLastName))				+ "&";
	postData += (CommonClass.preparePostString(this.txtFirstName))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbJobTitle))				+ "&";

	postData += (CommonClass.preparePostString(this.txtBusinessPhone))			+ "&";
	postData += (CommonClass.preparePostString(this.txtExtension))				+ "&";
	postData += (CommonClass.preparePostString(this.txtMobilePhone))			+ "&";
	postData += (CommonClass.preparePostString(this.txtFaxNo))					+ "&";

	postData += (CommonClass.preparePostString(this.txtEmailAddress))			+ "&";

	postData += (CommonClass.preparePostString(this.txtAddress))				+ "&";
//	postData += (CommonClass.preparePostString(this.cmbCity))					+ "&";
	postData += (CommonClass.preparePostString(this.cmbState))					+ "&";
	postData += (CommonClass.preparePostString(this.txtZipCode))				+ "&";

	postData += (CommonClass.preparePostString(this.txtNotes))					+ "&";

	postData += "ADDRESSNO=" + (cntctdetails.ADDRESSNO.toString())				+ "&";
	postData += "ADDRESSGUID=" + (cntctdetails.ADDRESSGUID.toString())			+ "&";
	postData += "COMMUNICATIONID=" + (cntctdetails.COMMUNICATIONID.toString())	+ "&";
	postData += "EMAILID=" + (cntctdetails.EMAILID.toString())					+ "&";
	postData += "USERID=" + (CommonClass.UserID)								+ "&";
	postData += "NOTEID=" + (cntctdetails.NOTEID.toString())					+ "&";

	postData += "CITYNO=" + (ctlCity.SelectedCityNo.toString())					+ "&";
	postData += "CITYNAME=" + escape(StringUtil.trim(ctlCity.CityName))			+ "&";
	
	postData += (CommonClass.preparePostString(this.chkActive));

	return postData;	
}

private function saveData(action:String, data:String=""):void{
	BusySpinner.getInstance().play(Application.application.ModuleCvs);
	var params:String = "OPERATION=CONTACT_UPDATEDETAILS" +
						//"&PKID="+this.key+
						(data.length>0?"&":"") +data;

	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateContactDetails);
	ws.processServiceRequest(params);
}

private function callForUpdateContactDetails(event:ProcessServiceRequestResultEvent):void{
	
	var response:XML = XML(event.result);
	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();
		
		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else{
			var ni:NavigationInfo = this.NavInfo.copy();
			ni.destinationNavObj.pkID = this.key;
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate( ni);
		}
	}else{
		BusySpinner.getInstance().stop();
		Alert.show( String(response.RESPONSE.MESSAGE) );	
	}	
}

private function validate():Boolean{
	var v:Array = new Array();
	v.push(accNameV,fnameV,lnameV);
	v.push(stateV, zipV,phoneV, extnV);
	v.push(mobileV, faxV,emailV);
	
	var result:Array = Validator.validateAll(v);
	
	var cityValidation:ValidationResultEvent = this.ctlCity.validate(fiCity.required);
	if(cityValidation.type == ValidationResultEvent.INVALID)
		result.push(cityValidation);

	if(result.length>0){
		var vWin:ValidationErrorWin = new ValidationErrorWin();
		vWin.Messages = result;
		vWin.title = "Save : Contact Details";
		
		PopUpManager.addPopUp(vWin,this,true);
		PopUpManager.centerPopUp(vWin);
		return false;
	}
	return true;
}
private function initializeForDirtyCheck():void{

	if(!_cityLoaded || !_detailsLoaded) return;

	BusySpinner.getInstance().stop();
	DirtyChecker.getInstance().setInitialControl(this);
}

public function promptToSave():void{
	Alert.buttonWidth = 90;
	var yesNoCancelAlert: Alert = Alert.show("Do you want to save before exiting?", "Save",Alert.YES | Alert.NO | Alert.CANCEL, Application.application.ModuleCvs,performAlertAction);
}

private function performAlertAction(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		handleSubmitClick();
	}else if(event.detail == Alert.NO){
		DirtyChecker.getInstance().resetDirtyChecker();
		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else
			handleCancelClick();

	}else{
		// PERFORM NO ACTION - STAY BACK TO THE PAGE
	}
}